package cn.edu.swu.syz.controller;

import cn.edu.swu.syz.db.BookResultSetVisitor;
import cn.edu.swu.syz.db.DatabaseService;
import cn.edu.swu.syz.entity.Book;
import cn.edu.swu.syz.utils.HtmlHelper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/updateBook")
public class UpdateBookServlet extends HttpServlet {
    private DatabaseService dbService;

    // 初始化：使用单例模式获取 DatabaseService（与项目其他部分保持一致）
    @Override
    public void init() {
        dbService = DatabaseService.getInstance(); // 关键：用单例，不要 new
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookId = request.getParameter("bookId");

        // 1. 验证 bookId 是否有效
        if (bookId == null || bookId.trim().isEmpty()) {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(HtmlHelper.wrapHtml("错误：未传入图书 ID"));
            return;
        }

        // 2. 查询图书信息（使用参数化查询避免 SQL 注入）
        String selectSQL = "select * from book where id = ?"; // 占位符
        try {
            // 假设 BookResultSetVisitor 支持参数化查询（若不支持，需修改其实现）
            List<Book> books = dbService.query(selectSQL, new BookResultSetVisitor(), bookId);

            // 3. 处理空结果（避免 IndexOutOfBoundsException）
            if (books == null || books.isEmpty()) {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write(HtmlHelper.wrapHtml("错误：未找到 ID 为 " + bookId + " 的图书"));
                return;
            }

            // 4. 生成修改表单
            Book book = books.get(0); // 此时列表非空，可安全获取
            String template = """
                <form action="./updateBook" method="post" style="line-height:3em">
                    <input type="hidden" name="id" value="%s"><br>
                    书名：<input type="text" name="name" value="%s"><br>
                    作者：<input type="text" name="author" value="%s"><br>
                    价格：<input type="text" name="price" value="%s"><br>
                    备注：<textarea rows="3" cols="22" name="memo">%s</textarea><br>
                    日期：<input type="date" name="publish" value="%s"><br><br> <!-- 使用 date 类型 -->
                    <input type="submit" value="修改图书">
                </form>
            """;
            // 格式化日期为 yyyy-MM-dd（与数据库 date 类型匹配）
            String publishDate = book.getPublish() != null ?
                    book.getPublish().toString() : ""; // 假设 getPublish() 返回 LocalDate 或格式化的字符串

            response.setContentType("text/html;charset=UTF-8");
            try (Writer writer = response.getWriter()) {
                String form = String.format(template,
                        book.getId(),
                        escapeHtml(book.getName()), // 防 XSS
                        escapeHtml(book.getAuthor()),
                        book.getPrice(),
                        escapeHtml(book.getMemo()),
                        publishDate);
                writer.write(HtmlHelper.wrapHtml(form));
            }

        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException("查询图书失败：" + e.getMessage());
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 设置请求编码（避免中文乱码）
        request.setCharacterEncoding("UTF-8");

        // 2. 获取表单参数
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String price = request.getParameter("price");
        String memo = request.getParameter("memo");
        String publish = request.getParameter("publish");

        // 3. 验证必要参数
        if (id == null || name == null || price == null) {
            throw new ServletException("必要参数缺失");
        }

        // 4. 执行更新（使用参数化 SQL 避免注入）
        String updateSQL = "update book set name=?, author=?, price=?, memo=?, publish=? where id=?";
        try {
            // 调用支持参数化的 execute 方法（需修改 DatabaseService 实现）
            dbService.execute(updateSQL, name, author, price, memo, publish, id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException("修改图书失败：" + e.getMessage());
        }

        // 5. 重定向回图书列表
        response.sendRedirect("./books");
    }

    // 辅助方法：转义 HTML 特殊字符（防 XSS 攻击）
    private String escapeHtml(String content) {
        if (content == null) return "";
        return content.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }
}